package com.component.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.component.PropUtil;
import com.component.encrypt.EncryptUtil;
import com.component.mode.ReturnMsg;

public class HttpUtil {
	/**
	 * 发送数据
	 * 
	 * @param jsonData
	 *            表单数据
	 * @param sendType
	 *            post or get
	 * @param encrptType
	 *            加密 or 不加密
	 * @throws Exception
	 */
	public static ReturnMsg sendData(JSONObject jsonData, int sendType, int encrptType, String servletName) throws Exception {
		ReturnMsg rmsg = new ReturnMsg();
		JSONObject paramJson = new JSONObject();
		paramJson.put("encrptType", encrptType);

		if (encrptType == HttpConfig.encrypt_java)
			paramJson.putAll(EncryptUtil.encryptData(jsonData));
		else
			paramJson.putAll(jsonData);

		if (sendType == HttpConfig.send_post)
			rmsg = post(paramJson, HttpConfig.from_shunjin_yes, servletName);

		return rmsg;
	}

	@SuppressWarnings("deprecation")
	public static RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000).setConnectionRequestTimeout(6000)
			.setStaleConnectionCheckEnabled(true).build();

	public static ReturnMsg post(JSONObject json, String shunjin, String servletName) {
		ReturnMsg rmsg = new ReturnMsg();
		// 创建默认的httpClient实例.
		CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
		// 创建httppost
		HttpPost httppost = new HttpPost(PropUtil.getProperty("third.service.url") + "/" + servletName);
		// 创建参数队列
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		createFormParams(json, formparams);

		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httppost.setEntity(uefEntity);
			httppost.setHeader("shunjin", shunjin);
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String returnStr = EntityUtils.toString(entity, "UTF-8");
					rmsg = (ReturnMsg) JSONObject.toBean(JSONObject.fromObject(returnStr), ReturnMsg.class);
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return rmsg;
	}

	@SuppressWarnings("unchecked")
	private static void createFormParams(JSONObject json, List<NameValuePair> formparams) {
		Iterator<Entry<String, Object>> iter = json.entrySet().iterator();
		while (iter.hasNext()) {
			Entry<String, Object> entry = iter.next();
			formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue() + ""));
		}
	}
	//
}
